package com.snda.lib.proxy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import com.snda.lib.util.MD5Helper;

/**
 * 
 * @author zhangzhongqing
 * 
 *         该类用于快速的从给定的URL下载文件，并进行保存到本地 如果本地已经存在，则直接返回
 */
public class FileProxy {

	private String mUrl;
	private String mCacheDir = "/sdcard/snlib/";

	public FileProxy(String url, String cacheDir) {
		mUrl = url;
		mCacheDir = cacheDir;
	}

	private String getCachedFilePath() {

		String hash = MD5Helper.getStringMD5(mUrl);
		String hashDir = hash.substring(0, 1);
		hashDir = mCacheDir + hashDir;
		File f = new File(hashDir);
		if (!f.exists()) {
			f.mkdirs();
		}
		String fileExt = mUrl.substring(mUrl.lastIndexOf('.'));
		return hashDir + "/" + hash + fileExt;
	}

	public File getCachedFile() {

		File cachedFile = new File(getCachedFilePath());
		if (cachedFile.exists()) {
			return cachedFile;
		}

		// 从给定的URL位置开始读取
		InputStream is = null;
		if (is == null) {
			try {
				URL url = new URL(mUrl);
				is = (InputStream) url.getContent();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 写入到缓存文件中
		if (is != null && !cachedFile.exists()) {
			try {
				cachedFile.createNewFile();

				OutputStream out = new FileOutputStream(cachedFile);

				byte buf[] = new byte[1024];

				int len;
				while ((len = is.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.close();

				is.close();

			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

		return cachedFile;
	}

	public InputStream getInputStream() {

		File cachedFile = getCachedFile();
		if (cachedFile == null || cachedFile.exists() == false)
			return null;

		InputStream is = null;
		try {
			is = new FileInputStream(cachedFile);
		} catch (FileNotFoundException e) {

		}

		return is;
	}
}
